package com.cjd.common.adapter

import android.view.View
import android.view.ViewGroup
import androidx.core.view.contains
import androidx.viewpager.widget.PagerAdapter
import com.cjd.common.holder.BaseViewPagerHolder

/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/10/2
 * description viewPager 基类
 */
abstract class BasePagerAdapter<T> : PagerAdapter() {
    private var data = ArrayList<T>()

    override fun isViewFromObject(view: View, obj: Any) = view == obj

    override fun getCount() = data.size

    override fun getItemPosition(obj: Any): Int {
//        return super.getItemPosition(obj) // todo 解决无法刷新
        return POSITION_NONE
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        val viewType = getViewType(position)
        val holder = onCreateItemView(container, position, viewType)
        onBindItemView(holder, position, viewType)
        container.addView(holder.itemView)
        return holder.itemView
    }

    override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
        //todo 注释掉 否则：java.lang.UnsupportedOperationException: Required method destroyItem was not overridden
//        super.destroyItem(container, position, obj)
        if (obj is View && container.contains(obj as View)) {
            container.removeView(obj)
        }
    }

    fun getItem(position: Int): T {
        return data[position]
    }

    fun getAll(): ArrayList<T> {
        return data
    }

    fun getItemCount(): Int {
        return data.size
    }

    fun add(item: T) {
        data.add(item)
        notifyDataSetChanged()
    }

    fun add(index: Int, item: T) {
        data.add(index, item)
        notifyDataSetChanged()
    }

    fun addAll(collection: Collection<T>?) {
        if (collection != null) {
            data.addAll(collection)
            notifyDataSetChanged()
        }
    }

    fun replaceAll(collection: Collection<T>) {
        data.clear()
        addAll(collection)
    }

    protected fun getViewType(position: Int) = 0

    protected abstract fun onCreateItemView(
        container: ViewGroup,
        position: Int,
        viewType: Int
    ): BaseViewPagerHolder

    protected abstract fun onBindItemView(holder: BaseViewPagerHolder, position: Int, viewType: Int)

}